package com.lottery.game.websocket.listener;

import com.lottery.game.core.modules.service.app.OperationalSetService;
import com.lottery.game.core.modules.service.redis.RedisService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.util.List;
import java.util.Map;
import java.util.Set;

import lombok.extern.slf4j.Slf4j;

import static com.lottery.game.common.constants.GameConstants.CHAT_ID;
import static com.lottery.game.common.constants.GameConstants.RANDOM_USER_ID;
import static com.lottery.game.common.constants.GameConstants.USER_ID;

/**
 * 替换MyHandler.afterConnectionClosed
 * @author Administrator
 *
 */
@Slf4j
@Component
public class DisconnectEventListener {

	@Autowired
	private OperationalSetService operationalSetService;

	@Autowired
	private RedisService redisFeignClient;

//    @Autowired
//    private StompSessionHandler handler;

	//@EventListener
	public void onApplicationEvent(SessionDisconnectEvent event) {
		StompHeaderAccessor accessor =  StompHeaderAccessor.wrap(event.getMessage());
		log.info("Disconnected");

		String chatId = getIfExistFromHeader(accessor, CHAT_ID);
		String userId = getIfExistFromHeader(accessor, USER_ID);
		String randomUserId= getIfExistFromHeader(accessor, RANDOM_USER_ID);

		accessor.getSessionAttributes().remove(RANDOM_USER_ID, randomUserId);
		accessor.getSessionAttributes().remove(USER_ID, userId);

		List<Map<String, Object>> list=null;
//		int count = 0;
		if(!StringUtils.isEmpty(chatId) && !chatId.equals("sys_Overall")) {
			list = this.operationalSetService.queryVirtualNumberSetByNum(chatId);
//			if(!CollectionUtils.isEmpty(list)) {
//				String randoms = this.redisFeignClient.get(chatId);
//				if(!StringUtils.isEmpty(randoms)) {
//					count = Integer.parseInt(randoms);
//				}
//			} else {
//				this.redisFeignClient.del(chatId);
//			}
			if(CollectionUtils.isEmpty(list)) {
				this.redisFeignClient.delete(chatId);
			}
		}

		String sessionId = accessor.getSessionId();
		Set<String> keys = redisFeignClient.keys("*" + sessionId + "*");
		if(!CollectionUtils.isEmpty(keys)) {
			for (String key : keys) {
				redisFeignClient.delete(key);
			}
		}
	}

	private String getIfExistFromHeader(StompHeaderAccessor accessor, String key) {
		return accessor.getFirstNativeHeader(key);
	}

}
